package com.dq.service.sys.user.impl;

import com.dq.context.Constant;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.CustomerQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.domain.base.AbstractEntity;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.org.Org;
import com.dq.domain.org.OrgCustomerLevel;
import com.dq.domain.record.ServiceRecord;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.repository.org.OrgRepository;
import com.dq.service.org.OrgService;
import com.dq.service.sys.user.StaffUserService;
import com.dq.utils.EditCheckUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author luchangtong
 * @Date 2019/12/3 9:47
 */
@Service
public class StaffUserServiceImpl extends BaseRepositories implements StaffUserService {
    @Autowired
    private OrgService orgService;
    @Autowired
    OrgRepository orgRepository;
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void editBedNum(SysUser user,boolean flag) throws AdminException {
        Org org = dao.get(Org.class, user.getSection().getId());
        if(flag){
            Long userNum = serviceRecordRepository.countByServiceStatusAndSysDeptAndDeletedFalse(ServiceRecord.ServiceStatus.inService, (Org) user.getSection());
            if(org.getBedNum() - userNum <= 0){
                throw new AdminException("床位数不够");
            }
            org.setBedNum(org.getBedNum() - 1);
        }else {
            org.setBedNum(org.getBedNum() + 1);
        }
        orgRepository.save(org);
    }


    @Override
    public List<BossUser> findByWhere(CustomerQuery customerQuery) {
        customerQuery.format();
        Map<String, Object> query = customerQuery.parseMap();
        if(StringUtils.isNotEmpty(customerQuery.getValue())){
            Map<String, Object> keyQuery = new HashMap<>();
            keyQuery.put("cardNo"+BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(customerQuery.getValue()));
            keyQuery.put("username"+BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(customerQuery.getValue()));
            keyQuery.put("userRealcName"+BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(customerQuery.getValue()));
            query.put("keyQuery"+ BaseDaoImpl.orAndSqlStr, keyQuery);
            query.remove("value");
        }
        if(StringUtils.isNotEmpty(customerQuery.getOrgName())){
            query.put("section_name"+BaseDaoImpl.likeSqlStr,BaseAdminQuery.likeSql(customerQuery.getOrgName()));
            query.remove("orgName");
        }
        if(null!=customerQuery.getLevelId()){
            query.put("orgCustomerLevel_id",customerQuery.getLevelId());
            query.remove("levelId");
        }
        if(null!=customerQuery.getOrgId()){
            query.put("section_id",customerQuery.getOrgId());
            query.remove("orgId");
        }
       /* else {
            // 只显示负责门店信息
            List<Org> orgList = orgService.getListAllByUser();
            if(orgList == null || orgList.size() <= 0) {
                throw new AdminException("此账号无负责门店");
            }
            query.put("section" + BaseDaoImpl.inSqlStr, orgList);
        }*/
        if(null!=customerQuery.getStaffUserId()){
            query.put("staffUser_id",customerQuery.getStaffUserId());
            query.remove("staffUserId");
        }
        if(customerQuery.getStatus() != null){
            query.put("staffUserStatus",customerQuery.getStatus());
            query.remove("status");
        }
        if(customerQuery.getBeginTime()!=null){
            query.put("createTime"+ BaseDaoImpl.gteSqlStr,customerQuery.getBeginTime());
            query.remove("beginTime");
        }
        if(customerQuery.getEndTime()!=null){
            query.put("createTime"+BaseDaoImpl.lteSqlStr,customerQuery.getEndTime());
            query.remove("endTime");
        }
        query.remove("flag");
        List<BossUser> list =  dao.find(dao.query2Hql(BossUser.class,query),query);
        return list;
    }

    @Override
    public Long countByWhere(CustomerQuery customerQuery) {
        customerQuery.format();
        Map<String, Object> query = customerQuery.parseMap();
        if(StringUtils.isNotEmpty(customerQuery.getValue())){
            Map<String, Object> keyQuery = new HashMap<>();
            keyQuery.put("cardNo"+BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(customerQuery.getValue()));
            keyQuery.put("username"+BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(customerQuery.getValue()));
            keyQuery.put("userRealcName"+BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(customerQuery.getValue()));
            query.put("keyQuery"+ BaseDaoImpl.orAndSqlStr, keyQuery);
            query.remove("value");
        }
        if(StringUtils.isNotEmpty(customerQuery.getOrgName())){
            query.put("section_name"+BaseDaoImpl.likeSqlStr,BaseAdminQuery.likeSql(customerQuery.getOrgName()));
            query.remove("orgName");
        }
        if(null!=customerQuery.getLevelId()){
            query.put("orgCustomerLevel_id",customerQuery.getLevelId());
            query.remove("levelId");
        }
        if(null!=customerQuery.getOrgId()){
            query.put("section_id",customerQuery.getOrgId());
            query.remove("orgId");
        }
        /*else {
            // 只显示负责门店信息
            List<Org> orgList = orgService.getListAllByUser();
            if(orgList == null || orgList.size() <= 0) {
                throw new AdminException("此账号无负责门店");
            }
            query.put("section" + BaseDaoImpl.inSqlStr, orgList);
        }*/
        if(null!=customerQuery.getStaffUserId()){
            query.put("staffUser_id",customerQuery.getStaffUserId());
            query.remove("staffUserId");
        }
        if(customerQuery.getStatus() != null){
            query.put("staffUserStatus",customerQuery.getStatus());
            query.remove("status");
        }
        if(customerQuery.getBeginTime()!=null){
            query.put("createTime"+ BaseDaoImpl.gteSqlStr,customerQuery.getBeginTime());
            query.remove("beginTime");
        }
        if(customerQuery.getEndTime()!=null){
            query.put("createTime"+BaseDaoImpl.lteSqlStr,customerQuery.getEndTime());
            query.remove("endTime");
        }
        query.remove("flag");
        Long count =dao.count(dao.count2Hql(BossUser.class,query),query);
        return count;
    }

    public Query createWhereHql(CustomerQuery customerQuery,StringBuilder hql){
        if(StringUtils.isNotEmpty(customerQuery.getValue())){
            hql.append(" and (u.cardNo like:value");
            hql.append(" or u.username like:value");
            hql.append(" or u.userRealcName like:value)");
        }
        if(StringUtils.isNotEmpty(customerQuery.getOrgName())){
            hql.append(" and u.org.name like:orgName");
        }
        if(null!=customerQuery.getCustomerAgeBegin()){
            hql.append(" and u.memberAge>=:customerAgeBegin");
        }
        if(null!=customerQuery.getCustomerAgeEnd()){
            hql.append(" and u.memberAge<=:customerAgeEnd");
        }
        if(null!=customerQuery.getLevelId()){
            hql.append(" and u.orgCustomerLevel=:orgCustomerLevel");
        }
        if(null!=customerQuery.getOrgId()){
            hql.append(" and u.org=:org");
        }
        if(null!=customerQuery.getStaffUserId()){
            hql.append(" and u.staffUser=:staffUser");
        }
        if(null!=customerQuery.getFlag()){
            if(customerQuery.getFlag() == 1){
                hql.append(" and u.openid is NOT NULL");
            }else {
                hql.append(" and u.openid is NULL");
            }
        }
        if(customerQuery.getStatus() != null){
            hql.append(" and u.staffUserStatus=:status");
        }
        hql.append(" order by u.createTime desc");
        Query query = entityManager.createQuery(hql.toString());
        if(StringUtils.isNotEmpty(customerQuery.getValue())){
            query.setParameter("value","%"+customerQuery.getValue()+"%");
        }
        if(StringUtils.isNotEmpty(customerQuery.getOrgName())){
            query.setParameter("orgName","%"+customerQuery.getOrgName()+"%");
        }
        if(null!=customerQuery.getCustomerAgeBegin()){
            query.setParameter("customerAgeBegin",customerQuery.getCustomerAgeBegin());
        }
        if(null!=customerQuery.getCustomerAgeEnd()){
            query.setParameter("customerAgeEnd",customerQuery.getCustomerAgeEnd());
        }
        if(null!=customerQuery.getLevelId()){
            OrgCustomerLevel orgCustomerLevel = dao.get(OrgCustomerLevel.class,customerQuery.getLevelId());
            query.setParameter("orgCustomerLevel",orgCustomerLevel);
        }
        if(null!=customerQuery.getOrgId()){
            Org org = dao.get(Org.class,customerQuery.getOrgId());
            query.setParameter("org",org);
        }
        if(null!=customerQuery.getStaffUserId()){
            StaffUser staffUser = dao.get(StaffUser.class,customerQuery.getStaffUserId());
            query.setParameter("staffUser",staffUser);
        }
        if(customerQuery.getStatus() != null){
            query.setParameter("status",customerQuery.getStatus());
        }
        return query;
    }

    /**
     * 员工档案 添加
     */
    @Override
    public StaffUser save(StaffUser staffUser) {
        SysUser sysUser = shiroService.getUser();
        staffUser.setSection(sysUser.getSection());
        staffUser.setCreateUser(sysUser);
        staffUser.setUpdateUser(sysUser);

        staffUser.setVersion(Constant.VERSION_VALUE);
        staffUser.setDeleted(false);
        staffUser.setCreateTime(System.currentTimeMillis());
        staffUser.setLastModifyTime(System.currentTimeMillis());

        if(StringUtils.isBlank(staffUser.getCardNo())) {
            staffUser.setCardNo(AbstractEntity.generyDatetimeAndRandomNum(Constant.ORDERS_SUFF_COUNT));
        }
        if(staffUser.getStatus() == null) {
            staffUser.setStatus(SysUser.Status.on);
        }

        // 员工档案 判空
        judgeObject(staffUser, null);

        return staffUserRepository.save(staffUser);
    }
    /**
     * 员工账号
     * 基本信息判空
     */
    @Override
    public void judgeAcObject(StaffUser staffUser, Long id) {
        if(StringUtils.isBlank(staffUser.getUsername())) {
            throw new AdminException("登录账号为空");
        }
        StaffUser staffUserQuery = staffUserRepository.findByUsername(staffUser.getUsername());
        if(staffUserQuery != null) {
            if(id == null) {
                throw new AdminException("该账号已存在");
            }else {
                if(!staffUserQuery.getId().toString().equals(id.toString())) {
                    throw new AdminException("该手机号已存在");
                }
            }
        }
        if(StringUtils.isBlank(staffUser.getPassword())) {
            throw new AdminException("登录密码为空");
        }
        if(StringUtils.isBlank(staffUser.getUserRealcName())) {
            throw new AdminException("用户名不能为空");
        }
    }
    /**
     * 员工档案
     * 基本信息判空
     */
    @Override
    public void judgeObject(StaffUser staffUser, Long id) {
        // 判断参数是否为空
        if(staffUser.getBrithday() == null) {
            throw new AdminException("员工生日不能为空");
        }
        EditCheckUtil.idCardValidate(staffUser.getIdCardNo());
        if(StringUtils.isBlank(staffUser.getUserRealcName())) {
            throw new AdminException("用户名不能为空");
        }
        if(staffUser.getOrgPosition() == null) {
            throw new AdminException("请选择岗位");
        }
        if(staffUser.getSection() == null) {
            throw new AdminException("员工门店信息异常");
        }
        if(staffUser.getEntryTime() == null) {
            throw new AdminException("员工入职时间为空");
        }
        if(!EditCheckUtil.isMobileNO(staffUser.getMobile())){throw new AdminException("手机号格式不正确");}
        List<StaffUser> staffUserList = staffUserRepository.findByMobileAndDeletedFalse(staffUser.getMobile());
        if(staffUserList != null && staffUserList.size() > 0) {
            if(id == null) {
                throw new AdminException("该手机号已存在");
            }else {
                if(staffUserList.size() == 1) {
                    if(!staffUserList.get(0).getId().toString().equals(id.toString())) {
                        throw new AdminException("该手机号已存在");
                    }
                }else {
                    throw new AdminException("该手机号已存在");
                }
            }
        }
        if(StringUtils.isBlank(staffUser.getWorkingInfo())) {
            throw new AdminException("工作经历不能为空");
        }
    }


}
